import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import { baseUrlApi, baseOaApi } from "@/api/utils";
import {
  notepadListApi,
  notepadStoreApi,
  notepadUpdateApi,
  notepadDeleteApi,
  notepadShowApi,
} from "@/api/notepadApi";

export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    name: "",

  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "notepadId",
      width: 60
    },
    {
      label: "标题",
      prop: "title"
    },
    // {
    //   label: "内容",
    //   prop: "content",
    //   slot: "content",
    // },
    {
      label: "附件",
      prop: "attachment",
      slot: "attachment"
    },


    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 160
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await notepadListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  const formInline = ref();
  async function openDialog(title = "创建记事本", row?: FormItemProps) {
    if (`${title}` == "创建记事本") {
      formInline.value = {
        title: "创建记事本"
      };
    } else {
      const { result } = await notepadShowApi({ notepadId: row.notepadId });
      formInline.value = {
        title: "编辑记事本",
        notepadId: row.notepadId ?? "",
        notepadTitle: result?.title ?? "",
        content: result?.content ?? "",
        amount: result?.amount ?? "",
        attachment: result?.attachment ?? [],
      };

    }

    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {


            let params = {
              notepadId: curData.notepadId,
              content: curData.content,
              title: curData.notepadTitle,
              attachment: curData.attachment,
            }
            if (title === "创建记事本") {
              notepadStoreApi(toRaw(params)).then((res) => {
                if(res?.code === 200) {
                  chores();
                }

              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else {
              notepadUpdateApi(params).then((res) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row) {
    ElMessageBox.confirm('确定继续进行删除操作?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      notepadDeleteApi({ notepadId: row.notepadId }).then((res) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
  };
}
